import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  Keyboard,
  ScrollView,
  RefreshControl,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {LinearButton, TextButton} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {userLogout} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import DatePicker from 'react-native-date-picker';
import {queryItemsList} from '../../api/auction';
import {BASE_API} from '../../config';
import Layout from '../../config/LayoutConstants';
import LinearGradient from 'react-native-linear-gradient';
import {CachedImage} from 'react-native-img-cache';

const styles = StyleSheet.create({
  statusText: {
    width: 90,
    height: 20,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

class SelectNTF extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      isRefreshing: false,
      nfts: [],
    };
  }

  componentDidMount() {
    this.getList();
  }

  getList = () => {
    this.setState({
      isRefreshing: true,
    });
    queryItemsList({
      userToken: this.props.userInfo.token,
      address: this.props.userInfo.metamaskAddress,
      size: 999,
    })
      .then((res) => {
        console.log('------');
        console.log(res);
        let newNfts = res.data.rows.map((item) => {
          return {
            ...item,
            img: item.image,
          };
        });
        this.setState({
          nfts: [...newNfts],
          isRefreshing: false,
        });
      })
      .catch((err) => {
        console.log(err);

        this.setState({
          isRefreshing: false,
        });

        showToast(err.msg || 'failed');
      });
  };

  renderComponent = () => {
    let statusMap = {
      0: 'Invalid',
      1: 'Auctionable',
      2: 'On Auction',
    };

    let chainStatusMap = {
      0: 'Pending',
      1: 'On chain',
      2: 'Failed',
    };

    console.log(this.props.navigation.state.key);
    let newNtfs = [...this.state.nfts];

    console.log(Layout.WINDOW_HEIGHT);
    console.log(Layout.NAVIGATION_HEIGHT);

    let minHeight = Layout.WINDOW_HEIGHT - 160 - Layout.NAVIGATION_HEIGHT;

    // let contentHeight =
    //   parseInt((newNtfs.length + 3) / 3) * (20 + 90 + 20 + 100) + 20;

    return (
      <View style={{flex: 1, backgroundColor: '#fff'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text={
            this.props.navigation.state.params &&
            this.props.navigation.state.params.readOnly
              ? ' NFT Assets'
              : 'Select'
          }
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <ScrollView
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this.getList}
              tintColor={'white'}
              titleColor={'white'}
              title="Loading..."
            />
          }
          contentContainerStyle={{
            backgroundColor: '#160231',
            // paddingBottom: 20,
            // height: contentHeight,
          }}
          style={{backgroundColor: '#160231', flex: 1}}>
          <View
            style={{
              marginTop: 10,
              position: 'relative',
              // height: 200,
              paddingBottom: 20,
              borderTopLeftRadius: 30,
              borderTopRightRadius: 30,
              backgroundColor: 'white',
              paddingLeft: 20,
            }}>
            {!this.props.navigation.state.params ? (
              <Text style={{color: '#6A02F4', fontSize: 18, marginTop: 20}}>
                Select Item for auction
              </Text>
            ) : null}
            <View
              style={{
                flexDirection: 'row',
                flexWrap: 'wrap',
              }}>
              <View
                style={{
                  width: '33.3%',
                  alignItems: 'center',
                }}>
                <TouchableOpacity
                  style={{
                    width: 90,
                    height: 90,
                    marginTop: 20,
                    borderRadius: 15,
                    backgroundColor: '#F1F1F1',
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    let _this = this;
                    this.props.navigation.navigate('CreateNFT', {
                      refresh: () => {
                        console.log('触发修改回调');
                        _this.getList();
                      },
                    });
                  }}>
                  <Image
                    style={{width: 15, height: 15}}
                    source={require('../../assets/auction/new.png')}
                  />
                </TouchableOpacity>
                <Text
                  style={{
                    marginTop: 10,
                    color: '#3A3A3A',
                    fontSize: 14,
                  }}>
                  Create new NFT
                </Text>
              </View>
              <View
                style={{
                  width: '33.3%',
                  alignItems: 'center',
                }}>
                <TouchableOpacity
                  style={{
                    width: 90,
                    height: 90,
                    marginTop: 20,
                    borderRadius: 15,
                    backgroundColor: '#F1F1F1',
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    let _this = this;
                    this.props.navigation.navigate('ImportNFT', {
                      refresh: () => {
                        console.log('触发修改回调');
                        _this.getList();
                      },
                    });
                  }}>
                  <Image
                    style={{width: 15, height: 15}}
                    source={require('../../assets/auction/new.png')}
                  />
                </TouchableOpacity>
                <Text
                  style={{
                    marginTop: 10,
                    color: '#3A3A3A',
                    fontSize: 14,
                  }}>
                  Import NFT
                </Text>
              </View>
            </View>
            <Image
              style={{position: 'absolute', right: 50, top: -11}}
              source={require('../../assets/auction/auction.png')}
            />
          </View>
          <View
            style={{
              backgroundColor: 'white',
              minHeight: minHeight,
              flex: 1,
              width: '100%',
              paddingLeft: 20,
              paddingRight: 20,
            }}>
            <Image
              style={{
                height: 2,
                width: '100%',
              }}
              source={require('../../assets/auction/line.png')}></Image>
            <View
              style={{
                flexDirection: 'row',
                flexWrap: 'wrap',
                justifyContent: 'flex-start',
                paddingLeft: 20,
                paddingRight: 20,
              }}>
              {newNtfs.map((item) => {
                console.log(item.img);
                return (
                  <TouchableOpacity
                    style={{
                      // marginRight: 30,
                      paddingLeft: 4,
                      paddingRight: 4,
                      borderRadius: 10,
                      justifyContent: 'center',
                      alignItems: 'center',
                      marginTop: 20,
                      width: '33.3%',
                      position: 'relative',
                      alignSelf: 'flex-start',
                    }}
                    disabled={
                      item.status != 1 && !this.props.navigation.state.params
                    }
                    key={item.itemId}
                    onPress={() => {
                      if (
                        this.props.navigation.state.params &&
                        this.props.navigation.state.params.readOnly
                      ) {
                        this.props.navigation.navigate('NftDetail', {
                          nft: item,
                        });
                        return;
                      }

                      if (item.status != 1) {
                        return;
                      }

                      this.props.navigation.navigate('AuctionSet', {
                        nft: item,
                      });
                    }}>
                    <CachedImage
                      style={{
                        width: 90,
                        height: 90,
                        borderRadius: 10,
                      }}
                      cache={'force-cache'}
                      source={{uri: item.img}}></CachedImage>
                    {item.status == 0 ? (
                      <View
                        style={[
                          styles.statusText,
                          {backgroundColor: '#F1F1F1'},
                        ]}>
                        <Text style={{fontSize: 12, color: '#919191'}}>
                          {item.chainStatus == 1
                            ? statusMap[item.status]
                            : chainStatusMap[item.chainStatus]}
                        </Text>
                      </View>
                    ) : item.status == 1 ? (
                      <View
                        style={[
                          styles.statusText,
                          {backgroundColor: '#571DAA'},
                        ]}>
                        <Text style={{fontSize: 12, color: 'white'}}>
                          {item.chainStatus == 1
                            ? statusMap[item.status]
                            : chainStatusMap[item.chainStatus]}
                        </Text>
                      </View>
                    ) : item.status == 2 ? (
                      <LinearGradient
                        start={{x: 0, y: 1}}
                        end={{x: 1, y: 1}}
                        colors={['#CE18EC', '#6601F5']}
                        style={[
                          styles.statusText,
                          {backgroundColor: '#571DAA'},
                        ]}>
                        <Text style={{fontSize: 12, color: 'white'}}>
                          {item.chainStatus == 1
                            ? statusMap[item.status]
                            : chainStatusMap[item.chainStatus]}
                        </Text>
                      </LinearGradient>
                    ) : (
                      <View
                        style={[
                          styles.statusText,
                          {backgroundColor: '#F1F1F1'},
                        ]}>
                        <Text style={{fontSize: 12, color: '#FF6D6D'}}>
                          {item.chainStatus == 1
                            ? statusMap[item.status]
                            : chainStatusMap[item.chainStatus]}
                        </Text>
                      </View>
                    )}
                    <Text
                      numberOfLines={3}
                      ellipsizeMode="tail"
                      style={{
                        color: '#3A3A3A',
                        marginTop: 10,
                        // height: 20,
                        lineHeight: 20,
                      }}>
                      {item.name}
                    </Text>
                  </TouchableOpacity>
                );
              })}
            </View>
          </View>
          <View
            style={{
              width: '100%',
              backgroundColor: 'white',
              height: this.props.widgetLayout.show
                ? this.props.widgetLayout.height
                : 0,
            }}></View>
        </ScrollView>
        {/* <LinearButton
          buttonStyle={{
            alignSelf: 'center',
            width: 150,
            marginBottom: 50,
          }}
          onPress={() => {}}
          text={'Next'}></LinearButton> */}
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({
  userLogout: (item) => dispatch(userLogout()),
});

export default connect(mapStateToProps, mapDispatchToProps)(SelectNTF);
